package com.atguigu.szdz.dcsyl.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/img")
public class ImageController {

    @GetMapping("/image")
    public ResponseEntity<Resource> serveImage(@RequestParam String path) {
        System.out.println("ppppppppppp:" + path);
        try {
            // 指定D盘img文件夹下的1.png图片路径
            Path filePath = Paths.get(path);
            Resource resource = new FileSystemResource(filePath);

            // 设置响应头，指定内容类型为图片类型，这里以PNG为例
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"1.png\"");
            headers.add(HttpHeaders.CACHE_CONTROL, "must-revalidate, post-check=0, pre-check=0");
            headers.add(HttpHeaders.PRAGMA, "public");
            headers.add("Expires", "0");
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE); // 根据实际文件类型调整，例如：MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_GIF_VALUE等

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (Exception e) {
            return ResponseEntity.notFound().build(); // 文件不存在时返回404状态码
        }
    }
}